﻿using System;
using System.Data;
using Tyche.DAO.Mapper;

namespace Tyche.DAO.Transaction
{
    public abstract class TycheTransactionManager
    {
        [ThreadStatic]
        private static TycheTransaction tycheTrans;

        /// <summary>
        /// 创建TycheTransaction
        /// </summary>
        /// <param name="level"></param>
        /// <returns></returns>
        public static TycheTransaction BuildTransaction(IsolationLevel level)
        {
            if (tycheTrans == null)
            {
                tycheTrans = new TycheTransaction(level);
            }

            return tycheTrans;
        }

        /// <summary>
        /// 是否需要事务
        /// </summary>
        /// <returns></returns>
        public static bool IsNeddTransaction()
        {
            return tycheTrans != null;
        }

        /// <summary>
        /// 获取Mapper
        /// </summary>
        /// <returns></returns>
        public static ITycheMapper GetMapper()
        {
            return tycheTrans.CreateMapper();
        }

        /// <summary>
        /// 获取DbTransaction
        /// </summary>
        /// <returns></returns>
        public static IDbTransaction GetDbTransaction()
        {
            return tycheTrans.BeginTransaction();
        }

        /// <summary>
        /// 释放TycheTransaction
        /// </summary>
        public static void Dispose()
        {
            tycheTrans = null;
        }
    }
}
